﻿using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace ZhongJia.Lock.Infrastructure.Web
{
    public class BaseController : Controller
    {
        [NonAction]
        protected IActionResult Sucessed(object data = null)
        {
            return Json(data ?? new object());
        }

        protected IActionResult Error(string error, string errorDescription)
        {
            return BadRequest(new { Error = error, error_description = errorDescription });
        }

        [NonAction]
        public IActionResult ErrorToJson()
        {
            var errorMessage = string.Empty;
            foreach (var kvp in ModelState)
            {
                var error = kvp.Value.Errors.Select(e => e.ErrorMessage).FirstOrDefault();
                if (!string.IsNullOrEmpty(error))
                {
                    errorMessage += $",{error}";
                }
            }
            return Json(new
            {
                successed = false,
                message = errorMessage.Trim(',')
            });
        }
    }
}
